package test.yzx.pproject.testView;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;


public class TopPartScrollView extends ScrollView {

    public TopPartScrollView(Context context) {
        this(context, null);
    }
    public TopPartScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public TopPartScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    private View topView;
    private ScrollCheckListener bottomView;


    /* 将初始化View变量 */
    @Override
    protected void onFinishInflate() {
        ViewGroup childView = (ViewGroup) getChildAt(0);
        if(childView.getChildCount() != 2)
            throw new IllegalStateException("PartScrollView`s child must hold two children");
        topView = childView.getChildAt(0);
        bottomView = (ScrollCheckListener)childView.getChildAt(1);
    }
    /* 将childView的第二个childView的高度设置为100% */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        ((View)bottomView).getLayoutParams().height = getMeasuredHeight();
    }
    /* 让每个touch事件都必须经过onInterceptTouchEvent处理 */
    @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        super.requestDisallowInterceptTouchEvent(false);
    }


    /** 跳过本次touch流程的onInterceptTouchEvent(有childView横向滑动冲突可以调用) */
    public void requestDisallowInterceptTouchEvent(){
        super.requestDisallowInterceptTouchEvent(true);
    }


    private float downY;

    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getActionMasked()){
            /* DOWN */
            case MotionEvent.ACTION_DOWN:
                downY = ev.getY();
                return super.onInterceptTouchEvent(ev);
            /* MOVE */
            case MotionEvent.ACTION_MOVE:
                if(getScrollY() < topView.getHeight())
                    return super.onInterceptTouchEvent(ev);
                if(bottomView.atScrollTop()){
                    float distanceY = ev.getY() - downY;
                    return (distanceY > 0) && super.onInterceptTouchEvent(ev);
                }else
                    return false;
            /* UP & DEFAULT */
            case MotionEvent.ACTION_UP:
            default:
                return super.onInterceptTouchEvent(ev);
        }
    }



    /**  */
    public interface ScrollCheckListener{
        /** scrollY的状态是否在最顶 */
        boolean atScrollTop();
    }

}
